<template>
  <div>
    <title><%= VUE_APP_TITLE %></title>
    <div class="notice-bar">
      <div class="notice-vertical">
        <transition-group name="notice-fade" tag="div">
          <div
            v-if="noticeList.length"
            :key="noticeIndex"
            class="notice-item"
          >
            {{ noticeList[noticeIndex].content }}
          </div>
          <div
            v-else
            key="empty"
            class="notice-item"
          >
            暂无公告
          </div>
        </transition-group>
      </div>
    </div>
    <div class="nav-bar">
      <div class="nav-left">
        <span class="logo">佩紫方衡娱乐系统</span>
      </div>
      <div class="nav-right">
        <span @click="openUserDialog" style="cursor:pointer; color:#4a6cf7; text-decoration:underline;">
          欢迎您，{{ userInfo.nickname || userInfo.username}}
          <span v-if="userInfo.role" :class="['role-badge', userInfo.role.toLowerCase()]">
            {{ roleLabel(userInfo.role) }}
          </span>
        </span>
        <template v-if="userInfo.role === 'ADMIN'">
          <button class="nav-btn" @click="goAdmin">管理后台</button>
        </template>
        <button class="logout-btn" @click="logout">退出登录</button>
      </div>
    </div>
    <div class="main-center">
      <div class="bg-image"></div>
      <div class="start-game-bar">
        <button class="start-game-btn" @click="startGame">开始游戏</button>
      </div>
    </div>

    
    <!-- 用户弹出层 -->
    <el-dialog title="用户信息" :visible.sync="showUserDialog" width="400px">
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="userForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action=""
            :http-request="uploadUserAvata"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveUserInfo">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserInfo,updateUserInfo,getNoticeList,logout,uploadAvatar } from '@/api/user'
import { baseURL } from '@/utils/request'

export default {
  name: 'Index',
  data() {
    return {
      //用户信息(非登录返回)
      userInfo: {
        userid: '',
        username: '',
        email: '',
        role: '', // 用户角色 'ADMIN', 'VIP', 'USER'
        nickname: '',
        avatar: '',
      },
      //用户弹出层
      showUserDialog: false,
      //用户表单
      userForm: {
        username: '',
        nickname: '',
        avatar: ''
      },
      //公告列表
      noticeList: [],
      noticeIndex: 0,
      noticeTimer: null,
      imageUrl: ``,//头像
      //排行榜
      rankList: [
        { id: '1001', name: '张三', level: '无极（返璞归真）', levelCode: 9 },
        { id: '1002', name: '李四', level: '宗师（自成流派）', levelCode: 8 },
        { id: '1003', name: '王五', level: '坐照（牌桌掌控）', levelCode: 7 },
        { id: '1004', name: '赵六', level: '入神（心理博弈）', levelCode: 6 },
        { id: '1005', name: '小明', level: '通幽（算牌预判）', levelCode: 5 },
        { id: '1006', name: '小红', level: '巧者（灵活应变）', levelCode: 4 },
        { id: '1007', name: '小刚', level: '熟手（基础策略）', levelCode: 3 },
        { id: '1008', name: '小李', level: '入门（知晓规则）', levelCode: 2 },
        { id: '1009', name: '小赵', level: '懵懂（初碰牌桌）', levelCode: 1 }
      ],
      ws: null,
    }
  },
  //进入页面的时候初始化页面
  created() {
    this.checkLogin()
    this.fetchNotices()
    this.updateUserinfoForNickName()
    if(this.userInfo.avatar){
        this.imageUrl = `${baseURL}/user/api/file/avatars/${this.userInfo.userid}/${this.userInfo.avatar}`
    }else {
    this.imageUrl = require('@/assets/user/avatar.jpeg')
    }
  },
  mounted() {
    // 监听窗口焦点变化，防止多标签页同步
    window.addEventListener('focus', this.checkLogin)
  },
  beforeDestroy() {
    if (this.noticeTimer) clearInterval(this.noticeTimer)
    window.removeEventListener('focus', this.checkLogin)
  },
  methods: {
    //获取公告列表
    async fetchNotices() {
      try {
        const res = await getNoticeList(0, 10)
        this.noticeList = res.content || []
        this.startNoticeScroll()
      } catch (e) {
        this.$message.error('获取公告失败，请稍后再试')
        this.noticeList = []
      }
    },
    startNoticeScroll() {
      if (this.noticeTimer) clearInterval(this.noticeTimer)
      if (this.noticeList.length > 1) {
        this.noticeTimer = setInterval(() => {
          this.noticeIndex = (this.noticeIndex + 1) % this.noticeList.length
        }, 5000)
      }
    },
    //检查登录状态
    checkLogin() {
      const token = localStorage.getItem('token')
      const info = localStorage.getItem('userInfo')
      if (!token || !info) {
        this.$message && this.$message.warning('登录信息已过期，请重新登录')
        this.$router.replace('/')
        return
      }
      try {
        this.userInfo = JSON.parse(info)
      } catch (e) {
        this.userInfo = { username: '', email: '' , userid: '' }
      }
    },
    //获取用户昵称
    async updateUserinfoForNickName(){
      // 调用后端接口获取最新用户信息
      try {
        const res = await getUserInfo(this.userInfo.userid)
        // 接口返回的是 id，这里转换为 userid，整体替换 userInfo 保证响应式
        this.userInfo = {
          userid: res.id || this.userInfo.userid,
          username: res.username || this.userInfo.username,
          email: res.email || this.userInfo.email,
          role: res.role || this.userInfo.role,
          nickname: res.nickname || this.userInfo.nickname,
          avatar: res.avatar || this.userInfo.avatar
        }
      } catch (e) {
        // 拉取失败可选处理
        this.$message.error('获取用户信息失败，请重试')
      }
    },
    //获取用户信息
    async openUserDialog() {
      try {
        // 获取userinfo里面的id
        const userId = this.userInfo.userid
        if (!userId) {
          this.$message.error('用户ID不存在，请重新登录')
          return
        }
        // 调用后端接口获取最新用户信息
        const res = await getUserInfo(userId)
        // 更新表单数据
        this.userForm = {
          username: res.username || '',
          nickname: res.nickname || ''
        }
        this.showUserDialog = true
      } catch (e) {
        this.$message.error('获取用户信息失败，请重试')
      }
    },
    //保存用户的信息
    async saveUserInfo() {
      try {
        // 更新用户信息
        const updatedUserInfo = await updateUserInfo(this.userInfo.userid, this.userForm)
        this.userInfo = { ...this.userInfo, ...updatedUserInfo }
        this.$message.success('信息已更新')
        this.showUserDialog = false
      } catch (e) {
        this.$message.error('保存失败，请重试')
      }
    },
    //图片大小验证
    beforeAvatarUpload(file) {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('头像只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('头像大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //头像上传
    uploadUserAvata(file){
      uploadAvatar(this.userInfo.userid, file.file).then((res) => {
        this.userInfo.avatar = res
        this.imageUrl = `${baseURL}/user/api/file/avatars/${this.userInfo.userid}/${this.userInfo.avatar}`
        this.$message.success('头像上传成功')
      }).catch((e) => {
        this.$message.error('头像上传失败')
      })
    },
    //处理头像回显
    handleAvatarSuccess(response, file) {
      if(file.raw){
         this.imageUrl = `${baseURL}/user/api/file/avatars/${this.userInfo.userid}/${this.userInfo.avatar}`
      }else {
      this.imageUrl = require('@/assets/user/avatar.jpeg')
      }
    },
    //用户身份显示
    roleLabel(role) {
      switch (role) {
        case 'ADMIN': return '管理员'
        case 'VIP': return 'VIP'
        case 'USER': return '普通用户'
        default: return role
      }
    },
    startGame() {
      if (this.ws && this.ws.readyState === 1) {
        this.$router.push('/player-room')
        return
      }
      this.ws = new WebSocket('ws://localhost:1314')
      this.ws.onopen = () => {
        this.$router.push('/player-room')
      }
      this.ws.onmessage = (event) => {
        // 处理服务器推送的消息
        console.log('收到消息:', event.data)
      }
      this.ws.onclose = () => {
        // 连接关闭时可选提示
      }
      this.ws.onerror = (err) => {
        this.$message ? this.$message.error('连接服务器失败') : alert('连接服务器失败')
        console.error(err)
      }
    },
    //退出登录
    logout() {
      //localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      logout().then(() => {
        this.$message && this.$message.success('已退出登录')
        this.$router.replace('/')
      }).catch(err => {
        this.$message && this.$message.error('退出登录失败，请稍后再试')
      })
    },
    goAdmin() {
      this.$router.push('/admin')
    },
  }
}
</script>

<style scoped>
/* 公告开始 */
.notice-bar {
  width: 100%;
  height: 31px;
  background: #fffbe6;
  overflow: hidden;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f5e7b2;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  justify-content: center;
}

.notice-vertical {
  width: 100%;
  height: 31px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.notice-item {
  width: 100%;
  text-align: center;
  color: #b47d00;
  font-size: 15px;
  line-height: 31px;
  position: absolute;
  left: 0;
  top: 0;
}

.notice-fade-enter-active,
.notice-fade-leave-active {
  transition: all 0.5s;
}
.notice-fade-enter {
  transform: translateY(100%);
  opacity: 0;
}
.notice-fade-enter-to {
  transform: translateY(0);
  opacity: 1;
}
.notice-fade-leave {
  transform: translateY(0);
  opacity: 1;
}
.notice-fade-leave-to {
  transform: translateY(-100%);
  opacity: 0;
}
/* 公告结束 nav-bar开始 */
.nav-bar {
  width: 100%;
  height: 48px;
  background: #f7f9fa; /* 设置底色 */
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32px;
  box-sizing: border-box;
  border-bottom: 1px solid #eee;
  position: fixed;
  top: 31px;
  left: 0;
  z-index: 999;
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 24px;
}

.logo {
  font-weight: bold;
  color: #4a6cf7;
  font-size: 18px;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 24px;
  color: #4a6cf7;
  font-size: 15px;
  font-weight: 500;
}

.nav-field {
  color: #333;
  font-size: 15px;
  margin-left: 16px;
  font-weight: normal;
}

.main-center {
  width: 100vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 110px; /* nav-bar+notice-bar高度 */
}

.bg-image {
  width: 80vw;
  max-width: 1200px;
  height: 320px;
  background: url('@/assets/index.jpg') no-repeat center center;
  background-size: cover;
  border-radius: 24px;
  box-shadow: 0 4px 32px rgba(0,0,0,0.08);
  margin-bottom: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}
/* 开始游戏按钮区域 */
.start-game-bar {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80vw;
  max-width: 1200px;
}

.start-game-btn {
  padding: 32px 60px;
  font-size: 2rem;
  font-weight: bold;
  color: #fff;
  background: linear-gradient(90deg, #ff9800 0%, #ff5722 100%);
  border: none;
  border-radius: 32px;
  box-shadow: 0 4px 24px rgba(255,152,0,0.18);
  cursor: pointer;
  outline: none;
  animation: pulse 1.5s infinite;
  transition: transform 0.2s;
}

.start-game-btn:hover {
  transform: scale(1.08);
  background: linear-gradient(90deg, #ff5722 0%, #ff9800 100%);
}

.nav-btn {
  margin-left: 18px;
  padding: 6px 18px;
  background: #4a6cf7;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
}
.nav-btn:hover {
  background: #2d4fd7;
}

.recharge-input {
  width: 90%;
  padding: 10px;
  margin-bottom: 16px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 1rem;
  outline: none;
}
.recharge-btn {
  width: 100%;
  padding: 12px 0;
  background: linear-gradient(90deg, #4a6cf7 0%, #67c23a 100%);
  color: #fff;
  border: none;
  border-radius: 24px;
  font-size: 1.1rem;
  font-weight: bold;
  cursor: pointer;
  transition: background 0.2s;
}
.recharge-btn:hover {
  background: linear-gradient(90deg, #67c23a 0%, #4a6cf7 100%);
}

.logout-btn {
  margin-left: 18px;
  padding: 6px 18px;
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
}
.logout-btn:hover {
  background: #d93026;
}
/* 角色铭牌 */
.role-badge {
  display: inline-block;
  margin-left: 8px;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 0.9em;
  font-weight: bold;
  color: #fff;
  vertical-align: middle;
}
.role-badge.admin {
  background: #e53935; /* 红色 */
}
.role-badge.vip {
  background: #ffd700; /* 金色 */
  color: #333;
}
.role-badge.user {
  background: #4a6cf7; /* 蓝色 */
}
.role-badge.admin,
.role-badge.vip {
  background-image: linear-gradient(135deg, rgba(255,255,255,0.45) 0%, transparent 60%), inherit;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.12), 0 1.5px 0 0 rgba(255,255,255,0.18) inset;
  position: relative;
  overflow: hidden;
}

/* 用户名铭牌动态高光动画 */
.role-badge.admin::after,
.role-badge.vip::after {
  content: '';
  position: absolute;
  left: -40%;
  top: -40%;
  width: 10px;           /* 更窄的高光线 */
  height: 180%;
  background: linear-gradient(120deg, rgba(255,255,255,0.0) 0%, rgba(255,255,255,0.95) 50%, rgba(255,255,255,0.0) 100%);
  transform: skewX(-20deg);
  animation: badge-shine 2.2s infinite linear;
  pointer-events: none;
  opacity: 0.8;         /* 亮度更高 */
}

@keyframes badge-shine {
  0% {
    left: -60%;
  }
  100% {
    left: 120%;
  }
}
/* 用户信息头像上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 80px;
  height: 80px;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 6px;
}
</style>